package cn.bookcycle.requestroom.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.bookcycle.requestroom.ConstantData.BusinessConstant;
import cn.bookcycle.requestroom.ConstantData.DBConstant;
import cn.bookcycle.requestroom.pojo.RoomForList;
import cn.bookcycle.requestroom.pojo.SecureData;
import cn.bookcycle.requestroom.util.AESUtil;
import cn.bookcycle.requestroom.util.DaoUtil;
import cn.bookcycle.requestroom.util.DataFormatConvert;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 网页视图类
 *
 * @author liufenglin
 * @date 2018年3月18日
 */
@Controller
public class WebPageController {
	private static final Logger logger = LoggerFactory.getLogger(WebPageController.class);
	
	@RequestMapping(value = "applyroom", method = RequestMethod.GET)
	public String applyRoom(String requestBody, Model model) {
		if (requestBody != null) {
			try {
				requestBody = URLDecoder.decode(requestBody, BusinessConstant.UTF8);
			} catch (UnsupportedEncodingException e) {
				logger.warn("applyroom请求，对requestBody进行URL解码异常！！！！！！");
			}
			logger.info("applyroom 收到的参数是：{}", requestBody);
			JSONObject jsonObject = null;
			String userId = null;
			String roomId = null;
			try {
				jsonObject = new JSONObject(requestBody);
				userId = jsonObject.getString(BusinessConstant.USER_ID);
				roomId = jsonObject.getString(BusinessConstant.ROOM_ID);
			} catch (JSONException e) {
				logger.warn("applyroom请求，解析requestBody为JOSNObject发生异常");
			} 
			model.addAttribute(BusinessConstant.USER_ID, userId);
			model.addAttribute(BusinessConstant.ROOM_ID, roomId);
		}
		return "applyroom";
	}
	
	@RequestMapping(value = "checklist")
	public String getCheckListByUserId(String userId, Model model) {
		logger.info("checklist请求已经到来！！！！！");
		if (userId != null) {
			// 往前端送userId属性
			model.addAttribute(BusinessConstant.USER_ID, userId);
		}
		// 先根据userId查询到所有的申请看房信息（这个版本先粗暴的查询，不搞分页查询），查询的时候根据时间排序
		String josnArrayStr = DaoUtil.getCheckAuthorizationById(userId);
		// 对查询到数据解析成JOSNArray
		JSONArray jsonArray = null;
		try {
			jsonArray = new JSONArray(josnArrayStr);
		} catch (JSONException e) {
			// 防止后面出现空指针异常！！！！
			jsonArray = new JSONArray();
			logger.warn(" getCheckListByUserId 对查询到数据解析成JOSNArray 出现异常！！！！！");
		}
		// 新建一个List来有序存储每一次申请看房的信息
		List<RoomForList> list = new ArrayList<RoomForList>();
		// 遍历JSONArray
		for (int i = 0; i < jsonArray.length(); ++i) {
			JSONObject jsonObject = null;
			// 从JSONArray中获取每一个JSONObject
			try {
				jsonObject = jsonArray.getJSONObject(i);
			} catch (JSONException e) {
				// 防止后面出现空指针异常
				jsonObject = new JSONObject();
				logger.warn("getCheckListByUserId 从JSONArray取JSONObject出现异常！！！！！");
			}
			// 将一个JSONObject转化为RoomForList对象
			RoomForList room = DataFormatConvert.JS2RoomForList(jsonObject);
			// 把一个新的RoomForList对象放入List
			list.add(room);
		}
		logger.info("传回前端的list是：{}", list);
		// 向前台传输List
		model.addAttribute(DBConstant.ROOMS, list);
		return "checklist";
	}
	
	@RequestMapping(value = "securedata", method = RequestMethod.POST)
	@ResponseBody
	public String getSecureData(String openLockId) {
		String secureData = null;
		logger.warn("收到请求门锁{}开锁加密数据请求！！！！",openLockId);
		net.sf.json.JSONObject jsonObject = null;
		SecureData sd = SecureData.getInstance(openLockId, BusinessConstant.OPEN_CMD);
		jsonObject = net.sf.json.JSONObject.fromObject(sd);
		try {
			secureData = AESUtil.encrypt(jsonObject.toString(), BusinessConstant.OPEN_LOCK_DATA_KEY);
		} catch (Exception e) {
			logger.warn("getSecureData函数AES加密出错！！！！\njsonObject:{}", jsonObject);
		}
		logger.info("secureData:{}", secureData);
		return secureData;
	}
}
